package cn.itsource.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginCheckFilter extends ZuulFilter {
    //过滤器类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //顺序
    @Override
    public int filterOrder() {
        return 1;
    }

    //判断是否应该检查登录，返回true表示要做登录检查
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //判断url是否是登录请求
        String requestURI = request.getRequestURI();
        if(StringUtils.hasLength(requestURI)&&requestURI.endsWith("login")){
            return false;
        }
        return true;
    }

    //做登录检查，如果请求头中没有token，说明没有登录
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        //设置编码
        response.setContentType("application/json;charset=utf-8");

        //获取请求头token，判断是否登录
        String token = request.getHeader("token");
        request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            //如果token为空，表示没有登录，返回提示登录信息，阻止请求继续往下执行，不放行
            Map<String,Object> result = new HashMap<>();
            result.put("success",false);
            result.put("message","您还未登录，请先登录");
            try {
                response.getWriter().print(JSON.toJSONString(result));
                //并且阻止请求继续往下执行：不放行
                currentContext.setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
